/*
	Leola Programming Language
	Author: Tony Sparks
	See license.txt
*/
package leola.frontend.parsers;

import leola.ast.ASTNode;
import leola.ast.Expr;
import leola.ast.VarDeclStmt;
import leola.frontend.LeolaParser;
import leola.frontend.Token;
import leola.frontend.tokens.LeolaErrorCode;
import leola.frontend.tokens.LeolaTokenType;

/**
 * @author Tony
 *
 */
public class VarDeclStmtParser extends StmtParser {

	/**
	 * @param parser
	 */
	public VarDeclStmtParser(LeolaParser parser) {
		super(parser);
	}

	/* (non-Javadoc)
	 * @see leola.frontend.parsers.StmtParser#parse(leola.frontend.Token)
	 */
	@Override
	public ASTNode parse(Token t) throws Exception {
		Token token = nextToken(); // consume VAR token
		
		/* get the identifier */		
		LeolaTokenType type = token.getType(); 
		if ( ! type.equals(LeolaTokenType.IDENTIFIER)) {
			getExceptionHandler().errorToken(token, this, LeolaErrorCode.MISSING_IDENTIFIER);
		}
		
		String varName = token.getText();
		
		token = nextToken();
		if ( !token.getType().equals(LeolaTokenType.EQUALS)) {
			getExceptionHandler().errorToken(token, this, LeolaErrorCode.INVALID_ASSIGNMENT);
		}
		
		/* get the value expression */
		ExprParser expr = new ExprParser(this);
		Expr value = (Expr)expr.parse(nextToken());
		
		ASTNode varDecl = new VarDeclStmt(varName, value);		
		
		setLineNumber(varDecl, currentToken());
		return varDecl;
	}
}

